<?php
    namespace App\Http\Controllers\Admin;
    use App\Http\Controllers\Controller;
	use \Illuminate\Http\Request;
	use Gregwar\Captcha\CaptchaBuilder;
	use DB;
	use Session;
	use Crypt;
    class LoginController extends Controller{
    		//渲染登录页面
            public function login(){
                    return view('admin.login.login_list');
           }
           //处理登录页面传递过来的数据
           public function login_do(Request $requset){

           		//自动验证
	           	$this->validate($requset , [
					'u_name'	=>'required|max:30',
					'u_password'=>'required',
					'code'		=>'required'
				],
				[
					'u_name.required' 		=> '用户名必须填写',
					'u_name.max'			=> '用户名最多填写30个字符（一个中文占用两个字符）',
					'u_password.required'	=> '密码必须填写',
					'code.required'			=>'验证码不能为空'
				]
				);

				//登录处理页面 接收传递过来的值
				$name = $requset->input('u_name');
				/*$pass = Crypt::encrypt($requset->input('u_password'));
                echo $pass;die;*/
				$pass = $requset->input('u_password');
				$code = $requset->input('code');
				//$word = Crypt::decrypt($pass);
				$codenu = Session::get('codenu');
				if($codenu == $code){
					$data = DB::table('mo_huser')
					->where('u_name','=',$name)
					->where('u_status','1')
					->first();
					$row = Crypt::decrypt($data->u_password);
					if($pass === $row){
						if(!$data){
							$title = array('content'=>'用户名或密码错误','url'=>'login');
							return view('admin.alert',['data'=>$title]);
						}else{
							$requset->session()->put('u_name',$name);
							$requset->session()->put('r_id',$data->u_rid);
							$up = DB::update("update mo_huser set u_time='".time()."' where id=".$data->id);
							return redirect('admin')->with('success','登录成功');
						}
					}else{
						return redirect()->back();
					}
				}else{
					$title = array('content'=>'验证码错误','url'=>'login');
					return view('admin.alert',['data'=>$title]);
				}
				
       		}
			//退出登录
			public function login_out(Request $request){
				if($request->session()->has('u_name')){
		            //移除session
		            $request->session()->pull('u_name',session('u_name'));
					$request->session()->pull('r_id',session('r_id')); 
		            return redirect('admin');
        	 	}
			}
			//验证码
			public function code($temp){
				//实例化验证码类：
				$build = new CaptchaBuilder();
				//设置验证码宽高
				$build->build(150,32);
				//获取验证码内容
				$cont = $build->getPhrase();
				//把验证码内容存入session
				Session::flash('codenu',$cont);
				//清除缓存；
				ob_clean(); 
				//把验证码数据以图片数据输出
				return response($build->output())->header("Content-type","image/jpeg");
			}

    }

